<template>
  <div class="my_page_container">
    <div class="bg-white">
      <AmyQueryItem
        search-label="公司名称"
        @make-search-condition="queryTable"
      />
    </div>
    <div class="bg-white">
      <q-table
        id="my-xls"
        bordered
        flat
        separator="cell"
        :tableTitle="tableTitle"
        :columns="columns"
        row-key="name"
        :rows="dbFilterList"
        :pagination="dbPagination"
        :rows-per-page-options="[10,20]"
        selection="multiple"
        v-model:selected="selectedItems"
      >

        <!--  插槽：表格头部左侧    -->
        <template v-slot:top-left>
          <q-input outlined dense color="base" v-model="filterText" :input-style="{ width: '150px'}">
            <template v-slot:append>
              <q-icon name="search" color="indigo" />
            </template>
          </q-input>
        </template>

        <!--  插槽：表格头部左侧    -->
        <template v-slot:top-right>
          <div class="q-gutter-sm">
            <q-btn
              dense
              unelevated
              color="secondary"
              label="新增"
              icon="mdi-comment-plus"
              @click="addDlgItem"
            />
            <q-btn
              dense
              unelevated
              color="amber"
              label="导入"
              icon="mdi-file-import"
            />
            <q-btn
              dense
              unelevated
              color="pink"
              label="导出"
              icon="mdi-database-export"
              @click="exportExcel"
            />
          </div>
        </template>

        <!--  插槽：某个单元格    -->
        <template #body-cell-typeId="props">
          <q-td :props="props">{{findCatalogLabel(companyTypeList, props.row.typeId)}}</q-td>
        </template>
        <template #body-cell-icon="props">
          <q-td :props="props"><q-icon :name="props.row.icon" color="orange" size="sm"/></q-td>
        </template>
        <template #body-cell-operation="props">
          <q-td :props="props">
            <q-btn flat round dense color="primary" icon="edit" @click="editDlgItem(props.rowIndex)">
              <q-tooltip>编辑</q-tooltip>
            </q-btn>
            <q-btn flat round dense color="red" icon="mdi-delete-empty" @click="deleteDlgItem(props.rowIndex)">
              <q-tooltip>删除</q-tooltip>
            </q-btn>
          </q-td>
        </template>

        <!--   底部插槽     -->
        <template v-slot:bottom>
          <AmyPagination :page-msg="dbPagination" @update="refreshTableAry"/>
        </template>
      </q-table>
      <CompanyDlg
        ref="myAddDlgRef"
        :item-data="getActiveItem()"
        :company-type-arr="companyTypeList"
        :icon-type-arr="iconTypeList"
        @cancel-company-item="cancelAddDlg"
        @submit-company-item="submitAddDlg"
      />

      <AmyDeleteDlg
        ref="myDelDlgRef"
        :selected-index="deletedIndex"
        @btnSubmit="submitDelDlg"
      />
    </div>
  </div>
</template>

<script lang="ts">
import { defineAsyncComponent, defineComponent, onMounted, reactive, ref, watch, onUnmounted } from 'vue';
import { useSysCatalogTbl } from '../../../hook/useSysCatalogTbl';
import { sysCatalogType, sysBaseUrlAPI } from '../../../util/SysBaseConst';
import api from 'axios';
import * as XLSX from 'xlsx';
import { useMessageNotify } from 'src/hook/common/useMessageNotify';
import BaseItem from 'pages/BaseItem.vue';
import { EStatusType, ItemType } from 'src/hook/common/useCommonVisitType';
import useCommonVisitDatabase from 'src/hook/common/useCommonVisitDatabase';
import { useCatalogTool } from 'src/hook/common/useCatalogTool';
import { CQueryParam } from 'src/components/basic/basicModel';

import { CompanyItem } from './CompanyModel';

const CompanyDlg = defineAsyncComponent(() => import('pages/sys/company/CompanyDlg.vue'));
const AmyDeleteDlg = defineAsyncComponent(() => import('components/basic/AmyDeleteDlg.vue'));
export type DeleteDlgInstance = InstanceType<typeof AmyDeleteDlg>;
export type CompanyDlgInstance = InstanceType<typeof CompanyDlg>;


export default defineComponent({
  name: 'CompanyIndex',
  extends: BaseItem,
  components: {
    CompanyDlg
  },

  setup (props, context) {
    //*********************************************************************************************
    //      消息通知
    //*********************************************************************************************
    //消息通知
    const {
      showMessage
    } = useMessageNotify();

    //*********************************************************************************************
    //      查询模块
    //*********************************************************************************************
    //查询输入参数
    let queryParam = reactive({
      name: '',
      startDate: '',
      endDate: ''
    });

    //有条件查询
    const queryTable = (s: CQueryParam) => {
      queryParam.name = s.name;
      queryParam.startDate = s.startDate;
      queryParam.endDate = s.endDate;

      //有条件查询
      loadList();
    }


    //*********************************************************************************************
    //      读取表格数据
    //*********************************************************************************************
    //检索响应数据
    const state = reactive({
      itemData: {
        id: 0,
        cname: '',
        typeId: 0,
        icon: '',
        address: '',
        privilege: 0,
        sortCode: '',
        description: '',
        parentId: 0,
        createTime: '',
        createUserId: 0,
        updateTime: '',
        updateUserId: 0
      }
    });


    //查询数据库
    const fetchApi = () => {
      const params = {
        cname: queryParam.name,
        startDate: queryParam.startDate,
        endDate: queryParam.endDate,
        pageNum: dbPagination.value.pageNum,
        pageSize: dbPagination.value.pageSize
      }
      return api.post(sysBaseUrlAPI.SYS_COMPANY_API_PAGE, {
        cname: queryParam.name,
        startDate: queryParam.startDate,
        endDate: queryParam.endDate,
        pageNum: dbPagination.value.pageNum,
        pageSize: dbPagination.value.pageSize
      });
    };

    //删除记录
    const deleteApi = (item: ItemType) => {
      return api.post(sysBaseUrlAPI.SYS_COMPANY_API_DELETE, { id: item.id });
    };

    //增加记录
    const confirmAddApi = (item: ItemType) => {
      return api.post(sysBaseUrlAPI.SYS_COMPANY_API_ADD, {
        id: item.id,
        cname: item.cname,
        typeId: item.typeId,
        icon: item.icon,
        address: item.address,
        privilege: item.privilege,
        sortCode: item.sortCode,
        description: item.description,
        parentId: item.parentId,
        createTime: '2020-01-01 00:30:00',
        createUserId: 45,
        updateTime: '2022-05-05 20:30:00',
        updateUserId: 230
      });
    };

    //修改记录
    const confirmEditApi = (item: ItemType) => {
      return api.post(sysBaseUrlAPI.SYS_COMPANY_API_UPDATE, {
        id: item.id,
        cname: item.cname,
        typeId: item.typeId,
        icon: item.icon,
        address: item.address,
        privilege: item.privilege,
        sortCode: item.sortCode,
        description: item.description,
        parentId: item.parentId,
        createTime: '',
        createUserId: 0,
        updateTime: '',
        updateUserId: 0
      });
    };

    const {
      dbList,
      dbFilterList,
      dbPagination,
      dbCurrentIndex,
      dbStatus,
      getActiveItem,
      filterList,
      loadList,
      addItem,
      editItem,
      deleteItem,
      cancelItem,
      confirmApi
    } = useCommonVisitDatabase(state.itemData, fetchApi, confirmAddApi, confirmEditApi, deleteApi);

    //*********************************************************************************************
    //      读取目录
    //*********************************************************************************************
    const {
      findCatalogLabel,
      findCatalogId
    } = useCatalogTool();

    const {
      companyTypeList,
      iconTypeList,
      getCatalog,
      removeCatalog
    } = useSysCatalogTbl();

    //*********************************************************************************************
    //      表格
    //*********************************************************************************************
    const columns = [
      {
        name: 'id',
        required: true,
        label: 'ID号',
        align: 'center',
        field: (row:any) => (row.id),
        sortable: true
      },
      { name: 'cname', align: 'center', label: '名称', field: 'cname' },
      { name: 'typeId', align: 'center', label: '类型', field: 'typeId' },
      { name: 'address', align: 'center', label: '地址', field: 'address' },
      { name: 'sortCode', align: 'center', label: '序码', field: 'sortCode' },
      { name: 'createTime', align: 'center', label: '创建时间', field: 'createTime' },
      { name: 'operation', align: 'center', label: '操作', field: 'operation' }
    ];

    //rows
    let tableTitle = ref('用户数据');
    let selectedItems = ref([]);
    let filterText = ref('');
    let myDelDlgRef = ref<DeleteDlgInstance|null>(null);
    let myAddDlgRef = ref<CompanyDlgInstance|null>(null);
    let deletedIndex = ref(0);

    //检索显示
    const searchTableAry = () => {
      filterList(filterText.value);
    }

    //添加用户
    const addDlgItem = () => {
      if (myAddDlgRef.value) {
        addItem();
        myAddDlgRef.value.show('新建企业信息');
      }
    }

    //编辑用户
    const editDlgItem = (row: number) => {
      if (myAddDlgRef.value) {
        editItem(row);
        myAddDlgRef.value.show('编辑企业信息');
      }
    }

    //删除用户
    const deleteDlgItem = (row: number) => {
      if (myDelDlgRef.value) {
        deletedIndex.value = row;
        myDelDlgRef.value.show('企业信息');
      }
    }

    //更新分页组件，检索条件不变
    const refreshTableAry = (pageNum: number) => {
      dbPagination.value.pageNum = pageNum;
      loadList();
    }

    //导出excel
    const exportExcel = () => {
      let workbook = XLSX.utils.table_to_book(document.getElementById('my-xls')); //需要在table上定义一个id
      try {
        XLSX.writeFile(workbook, 'BOX信息.xlsx');
      } catch (e) {
        showMessage('导出失败,失败信息:!');
      }
    }

    //*********************************************************************************************
    //      增加、修改模块
    //*********************************************************************************************
    //取消添加
    const cancelAddDlg = () => {
      //判断是增加还是修改
      if (dbStatus.value === EStatusType.ADD_TYPE) {
        cancelItem(0);
      }
    }
    //新建提交
    const submitAddDlg = (item: CompanyItem) => {
      console.log(item);
      confirmApi(item);
      loadList();
    }

    //*********************************************************************************************
    //      删除确认模块
    //*********************************************************************************************
    //提交确认对话框
    const submitDelDlg = (index: number) => {
      deleteItem(index);
    }

    //*********************************************************************************************
    //      启动模块
    //*********************************************************************************************
    //初始化
    const init = () => {
      //表格数据,无条件查询
      loadList();

      //目录
      getCatalog(sysCatalogType.COMPANY_TYPE_CODE);
      getCatalog(sysCatalogType.ICON_TYPE_CODE);
    }

    //监视检索框
    watch(filterText, () => {
      searchTableAry();
    });


    //挂载数据
    onMounted(() => {
      init();
    });

    //销毁数据
    onUnmounted(() => {
      removeCatalog(sysCatalogType.COMPANY_TYPE_CODE);
      removeCatalog(sysCatalogType.ICON_TYPE_CODE);
    });

    return {
      queryTable,

      columns,
      tableTitle,
      selectedItems,
      filterText,
      deletedIndex,
      myDelDlgRef,
      myAddDlgRef,

      searchTableAry,
      addDlgItem,
      editDlgItem,
      deleteDlgItem,
      refreshTableAry,

      dbList,
      dbFilterList,
      dbPagination,
      dbCurrentIndex,
      getActiveItem,

      findCatalogLabel,
      findCatalogId,
      companyTypeList,
      iconTypeList,

      cancelAddDlg,
      submitAddDlg,
      submitDelDlg,

      exportExcel
    }
  }
})
</script>

<style lang="scss" scoped>
.my_input {
  width: 150px;
}
</style>
